using Infrastructure;
using Infrastructure.Attribute;
using System.Text.Json;
using ZR.Model.System.Dto;
using ZR.ServiceCore.Services.IService;

namespace ZR.ServiceCore.Services
{
    /// <summary>
    /// 雷达基础信息查询服务实现
    /// </summary>
    [AppService(ServiceType = typeof(IWindLidarInfoService), ServiceLifetime = LifeTime.Transient)]
    public class WindLidarInfoService : IWindLidarInfoService
    {
        private readonly HttpClient _httpClient;
        private const string API_URL = "http://leida.vip.cpolar.cn/api/windlidar/info?commandtype=deviceInfo&commanddata=null";

        public WindLidarInfoService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        /// <summary>
        /// 获取雷达基础信息（异步方法）
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <returns></returns>
        public async Task<WindLidarInfoResultDto> GetWindLidarInfoAsync(WindLidarInfoRequestDto request = null)
        {
            try
            {
                // 设置默认参数
                if (request == null)
                {
                    request = new WindLidarInfoRequestDto
                    {
                        CommandType = "deviceInfo",
                        CommandData = null
                    };
                }

                // 构建查询参数
                var queryParams = new List<string>();
                if (!string.IsNullOrEmpty(request.CommandType))
                {
                    queryParams.Add($"commandtype={Uri.EscapeDataString(request.CommandType)}");
                }
                if (request.CommandData != null)
                {
                    queryParams.Add($"commanddata={Uri.EscapeDataString(request.CommandData.ToString())}");
                }

                var queryString = queryParams.Count > 0 ? "?" + string.Join("&", queryParams) : "";
                var fullUrl = API_URL;

                Console.WriteLine($"雷达基础信息查询 - 发送请求到: {fullUrl}");

                // 发送GET请求
                var response = await _httpClient.GetAsync(fullUrl);
                var responseContent = await response.Content.ReadAsStringAsync();

                Console.WriteLine($"雷达基础信息查询 - 响应状态码: {response.StatusCode}");
                Console.WriteLine($"雷达基础信息查询 - 响应内容: {responseContent}");
                
                // 添加调试信息
                Console.WriteLine($"雷达基础信息查询 - 开始解析JSON响应");

                if (response.IsSuccessStatusCode)
                {
                    // 解析响应
                    var infoResponse = System.Text.Json.JsonSerializer.Deserialize<WindLidarInfoResponseDto>(responseContent, new System.Text.Json.JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    });
                    
                    Console.WriteLine($"雷达基础信息查询 - JSON解析完成，Success: {infoResponse?.Success}, Data: {infoResponse?.Data != null}");
                    
                    if (infoResponse != null)
                    {
                        return ConvertToResultDto(infoResponse);
                    }
                    else
                    {
                        return new WindLidarInfoResultDto
                        {
                            IsSuccess = false,
                            Message = "响应解析失败",
                            Detail = "无法解析第三方接口响应",
                            QueryTime = DateTime.Now,
                            StatusDescription = "解析失败"
                        };
                    }
                }
                else
                {
                    return new WindLidarInfoResultDto
                    {
                        IsSuccess = false,
                        Message = $"HTTP请求失败: {response.StatusCode}",
                        Detail = responseContent,
                        QueryTime = DateTime.Now,
                        StatusDescription = "请求失败"
                    };
                }
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"雷达基础信息查询 - HTTP请求异常: {ex.Message}");
                return new WindLidarInfoResultDto
                {
                    IsSuccess = false,
                    Message = "网络请求失败",
                    Detail = ex.Message,
                    QueryTime = DateTime.Now,
                    StatusDescription = "网络异常"
                };
            }
            catch (System.Text.Json.JsonException ex)
            {
                Console.WriteLine($"雷达基础信息查询 - JSON解析异常: {ex.Message}");
                return new WindLidarInfoResultDto
                {
                    IsSuccess = false,
                    Message = "响应解析失败",
                    Detail = ex.Message,
                    QueryTime = DateTime.Now,
                    StatusDescription = "解析异常"
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"雷达基础信息查询 - 未知异常: {ex.Message}");
                return new WindLidarInfoResultDto
                {
                    IsSuccess = false,
                    Message = "系统异常",
                    Detail = ex.Message,
                    QueryTime = DateTime.Now,
                    StatusDescription = "系统异常"
                };
            }
        }

        /// <summary>
        /// 转换为结果DTO
        /// </summary>
        /// <param name="response">原始响应数据</param>
        /// <returns></returns>
        private WindLidarInfoResultDto ConvertToResultDto(WindLidarInfoResponseDto response)
        {
            return new WindLidarInfoResultDto
            {
                IsSuccess = response.Success,
                Message = response.Message ?? "无消息",
                Detail = response.Detail ?? "无详细信息",
                QueryTime = DateTime.Now,
                Data = response.Data,
                StatusDescription = GetInfoStatusDescription(response.Success)
            };
        }

        /// <summary>
        /// 获取信息查询状态描述
        /// </summary>
        /// <param name="success">请求是否成功</param>
        /// <returns></returns>
        private string GetInfoStatusDescription(bool success)
        {
            return success ? "查询成功" : "查询失败";
        }
    }
}
